/**
 * Create by Wanglei
 * Update by TianJing
 */
(function() {
    'use strict';

    var Utils = function() {
        this.villageAddress=$("#villageAddress");
        this.aroundInfo=$("#aroundInfo");
        this.buildYear=$("#buildYear");
        this.villageId=$("#villageId");

        this.street=$("#street");
        this.villageName=$("#villageName");
        this.buildingNo=$("#buildingNo");
        this.unitNo=$("#unitNo");
        this.houseNo=$("#houseNo");
        this.houseAddress=$("#houseAddress");
        this.houseAddressList=$("#houseAddress-list");
        // var $buildingNo=$("#buildingNo");
        // var $unitNo=$("#unitNo");
        // var $houseNo=$("#houseNo");
    };
    Utils.prototype = {
        houseYear:function(){
            var obj={};
            _.range(1840,moment().year()+1).forEach(function(it){
                obj[it]=it;
            });
            return obj;
        },
        checkVillageName:function (options) {
            // 检测小区名称功能
            var checkBtn=$(options.checkBtn);//检测小区的按钮
            var listPanel=$(options.listPanel);//显示列表面板
            var villageNameInput=$(options.villageNameInput);//小区搜索的输入框
            checkBtn.off("click").on("click",function (e) {
                var searchWord=villageNameInput.val();//获取搜索小区输入框内的内容
                var send={status:'AVAILABLE',numPerPage:'5'};//传入信息，状态为可用的，请求后台返回给5条匹配信息, 和搜索的小区内容信息
                if(searchWord!=""){
                    send[villageNameInput.attr("name")]=searchWord;
                    $.post(window.globalHost + "/agent-sys/admin/villageInfo/index.do",send).success(function (data) {
                        var detailInfo = common.transformData(data);
                        if(!!detailInfo.length){
                            var list= detailInfo.map(function (item, idx) {
                                return '<li>'+item.villageName.replace(searchWord, '<span>' + searchWord + '</span>')+'&nbsp;&nbsp;&nbsp;'+
                                    item.villageAddress.replace(searchWord, '<span>' + searchWord + '</span>')+'</li>';
                            });
                            listPanel.show().html("<span>类似小区已经存在了哦，请仔细核对避免重复添加</span><br>"+list.join(""));
                        }else{
                            listPanel.show().html("<ins>该小区尚未录入，请添加</ins>");
                        }
                    });
                }else{
                    listPanel.hide().html("");
                }
            });
        },
        searchVillageName:function (options) {
            var self=this;
            var listPanel=$(options.listPanel);
            var villageNameInput=$(options.villageNameInput);
            var timer="";
            var searchJSON={};
            $("body").on("click",function () {
                listPanel.hide();
            });
            villageNameInput.off("keyup").on("keyup",function (e) {
                var $this=$(this);
                var searchWord=$this.val();
                searchJSON[$this.attr("name")]=searchWord;
                self.street.val("");
                self.buildingNo.val("");
                self.unitNo.val("");
                self.houseNo.val("");
                self.houseAddress.val("");
                self.houseAddressList.html("");
                self.villageAddress.html("");
                self.aroundInfo.html("");
                self.buildYear.html("");
                listPanel.html("");
                clearTimeout(timer);
                if(searchWord===""){
                    //如果搜索框内输入的内容是空字符串那就清空所有的面板内容，并将地图定位到初始化情况

                    myMap.getPositionByBaiDuApi({
                        cityName:"上海"
                    });
                }else {
                    timer=setTimeout(function () {
                            //根据搜索小区的输入框的键盘输入事件，每次输入延迟500毫秒向服务器发送请求获取匹配的小区列表数据。
                            // 如果输入状态是连续输入信息，那就每次输入都清空上一次的定时器，禁止频繁输入请求
                            self.getVillageNameList({
                                villageNameInput:villageNameInput,
                                searchJSON:searchJSON,
                                listPanel:listPanel,
                                searchWord:searchWord,
                                callback:function (data) {
                                    // 组装根据列表数据拼装模板
                                    if(!!data.length){
                                        var list= data.map(function (item, idx) {
                                            return '<li>'+item.villageName.replace(searchWord, '<span>'+ searchWord + '</span>')+'&nbsp;&nbsp;&nbsp;'+
                                                item.villageAddress.replace(searchWord, '<span>' + searchWord + '</span>')+'</li>';
                                        });
                                        listPanel.show().html(list.join("")+"<p><span>**找不到您想要的小区?</span>&nbsp;&nbsp;<a href='javascript:;' id='addVillage'>点击添加小区</a></p>");
                                    }else{
                                        listPanel.show().html("<p><span>**找不到您想要的小区?</span>&nbsp;&nbsp;<a href='javascript:;' id='addVillage'>点击添加小区</a></p>");
                                    }
                                }
                            });
                    },500);
                }
            });
        },
        getVillageNameList:function (options) {
            var self=this;
            var searchJSON=options.searchJSON||{};
            var listPanel=$(options.listPanel);
            var villageNameInput=$(options.villageNameInput);
            var callback=options.callback;
            var send={status:'AVAILABLE',numPerPage:'5'};
            send=$.extend(send,searchJSON);//使send对象继承传入的 搜索词 searchJSON 对象
            $.post(window.globalHost + "/agent-sys/admin/villageInfo/index.do",send).success(function (data) {
                var detailInfo = common.transformData(data);
                !!callback&&$.isFunction(callback)&&callback(detailInfo);
                listPanel.off("click").on("click","li,#addVillage",function (ev) {
                    listPanel.hide();
                    var $this=$(this);
                    var selfNodeName=$this[0]['nodeName'];
                    var selfInfo=detailInfo[$this.index()];
                    if(selfNodeName==="LI"){
                        // 如果点击小区列表面板是小区信息，则自动填入输入框内小区信息并刷新百度地图的坐标点和周边信息
                        var selfVillageName=selfInfo.villageName,
                            selfAddress=selfInfo.villageAddress,
                            selfYear=selfInfo.buildYear?selfInfo.buildYear+"年":"",
                            selfPosition=[selfInfo.longitude,selfInfo.latitude];
                        villageNameInput.val(selfVillageName);
                        self.villageId.val(selfInfo.id);
                        self.villageAddress.html(selfAddress+"&nbsp;&nbsp;&nbsp;&nbsp;发现小区信息错误?<a data-id='"+selfInfo.id+"' href='javascript:;' id='editVillage'>点我编辑小区</a>");
                        self.buildYear.html(selfYear);
                        self.houseAddress.on("focus",function (e) {
                            var street=self.street.val();
                            var village=self.villageName.val();
                            var buildingNo=self.buildingNo.val();
                            var unitNo=self.unitNo.val();
                            var houseNo=self.houseNo.val();
                            var strDom=[];
                            strDom.push('<li>'+selfInfo.shiName+selfInfo.quName+(village?village:"")+(buildingNo?buildingNo+"号楼":"")+(unitNo?unitNo+"单元":"")+houseNo+'</li>');
                            strDom.push('<li>'+selfInfo.shiName+selfInfo.quName+(street?street:"")+(village?village:"")+(buildingNo?buildingNo+"号楼":"")+(unitNo?unitNo+"单元":"")+houseNo+'</li>');
                            strDom.push('<li>'+selfInfo.shengName+selfInfo.shiName+selfInfo.quName+(village?village:"")+(buildingNo?buildingNo+"号楼":"")+(unitNo?unitNo+"单元":"")+houseNo+'</li>');
                            strDom.push('<li>'+selfInfo.shengName+selfInfo.shiName+selfInfo.quName+(street?street:"")+(village?village:"")+(buildingNo?buildingNo+"号楼":"")+(unitNo?unitNo+"单元":"")+houseNo+'</li>');
                            self.houseAddressList.html(strDom.join("")).show();
                        });
                        self.houseAddress.on("blur",function (e) {
                            setTimeout(function () {
                                self.houseAddressList.hide();
                            },200);
                        });
                        self.houseAddressList.on("click","li",function (e) {
                            var $this=$(this);
                            self.houseAddress.val($this.html());
                        });
                        myMap.getPositionByBaiDuApi({
                            initPosition:selfPosition,
                            initSearchText:selfAddress
                        });

                    }else{
                        // 如果点击的是添加小区 #addVillage ,就弹框出现添加小区页面
                        common.openInsertDialog({
                            'url': './basicInfo/insertVillage.html',
                            'title': '添加小区',
                            'sAjaxSource': window.globalHost + '/agent-sys/admin/villageInfo/save.do',
                            'area': ['1000px', '600px'],
                            'btn': '保存',
                            ok: function () {

                            }
                        });
                    }
                    //阻止事件冒泡
                    ev.stopPropagation();
                });

                self.villageAddress.off("click").on("click","#editVillage",function (e) {
                    var $this=$(this);
                    var selfId=$this.attr("data-id");
                    common.openInsertDialog({
                        'url': './basicInfo/villageInfo.html?villageId='+selfId,
                        'title': '小区详情',
                        'sAjaxSource': window.globalHost + '/agent-sys/admin/villageInfo/update.do',
                        'area': ['1000px', '600px'],
                        'btn': '保存',
                        ok: function () {
                            villageNameInput.val("");
                            listPanel.html("");
                        }
                    });
                });
            });
        },
        createIconChosen:function (opt) {
            var $selector=$(opt.container);
            var initClass=opt.initClass;
            var $iconConfig=$selector.find("#icon-config");
            var $iconContent=$selector.find(".icon-content");
            var menuIconCss=$selector.find("[name='menuIconCss']");
            if(!!initClass && initClass!="xitongjichu"){
                $iconConfig.removeClass().addClass(initClass);
            }

            $selector.on("click","p,div",function () {
                $iconContent.hide();
            });
            $selector.on("click","#icon-config",function (e) {
                $iconContent.show();
                e.stopPropagation();
                e.preventDefault();
            });
            $selector.on("click",".toLeft",function (e) {
                var $now=$iconContent.find(".now");
                var $nowIndex=$now.index();
                if($nowIndex>=0 && $nowIndex<2){
                    $now.removeClass("now").addClass("prev trans").next().removeClass().addClass("now trans");
                }
                e.stopPropagation();
                e.preventDefault();
            });
            $selector.on("click",".toRight",function (e) {
                var $now=$iconContent.find(".now");
                var $nowIndex=$now.index();
                if($nowIndex>0 && $nowIndex<=2){
                    $now.removeClass("now").addClass("next trans").prev().removeClass().addClass("now trans");
                }
                e.stopPropagation();
                e.preventDefault();
            });
            $selector.on("click","li>.fa",function (e) {
                var $this=$(this);
                var selfClass=$this.attr("class");
                $iconConfig.removeClass().addClass(selfClass);
                menuIconCss.val(selfClass);
                e.stopPropagation();
                e.preventDefault();
            });
            $selector.on("click","div.page-controller",function (e) {
                $iconContent.show();
                e.stopPropagation();
                e.preventDefault();
            });
        }
    };
    window.utils = new Utils();
}).call(this);
